<template>
  <view class="container">
    <!-- 顶部大图轮播 -->
    <view v-if="imageList.length > 0" class="top-swiper-wrap">
      <swiper class="top-swiper" :indicator-dots="false" :current="current" @change="onSwiperChange">
        <swiper-item v-for="(img, idx) in imageList" :key="idx">
          <image :src="getImageUrl(img.url || img)" class="swiper-image" mode="aspectFill" @tap="previewImage(imageList, idx)" />
        </swiper-item>
      </swiper>
      <view class="img-count">{{current + 1}}/{{imageList.length}}</view>
    </view>
    <!-- 文章信息 -->
    <view v-if="article" class="article-header">
      <text class="article-title">{{article.title}}</text>
      <view class="article-meta">
        <text class="meta-item">作者：{{article.author || '未知'}}</text>
        <text class="meta-item">发布时间：{{formatDate(article.createTime)}}</text>
        <text class="meta-item">浏览：{{article.views || 0}}</text>
      </view>
    </view>
    <!-- 文章描述 -->
    <view v-if="article.description" class="article-desc">
      <text class="desc-text">{{article.description}}</text>
    </view>
    <!-- 图片列表 -->
    <view v-if="imageList.length > 0" class="image-list">
      <image
        v-for="(img, idx) in imageList"
        :key="idx"
        :src="getImageUrl(img.url || img)"
        class="list-image"
        mode="widthFix"
        @tap="previewImage(imageList, idx)"
      />
    </view>
    <!-- 文章内容 -->
    <view v-if="article.content" class="article-content">
      <text class="content-title">文章详情</text>
      <rich-text :nodes="article.content || '暂无内容'" class="content-text"></rich-text>
    </view>
    <view class="share-tip">此内容由他人分享给您</view>
    <!-- 加载状态 -->
    <view v-if="loading" class="loading">
      <text class="loading-text">加载中...</text>
    </view>
    <!-- 错误状态 -->
    <view v-if="error" class="error-container">
      <text class="error-text">{{errorMessage}}</text>
      <button class="retry-btn" @tap="loadArticle">重试</button>
    </view>
    <!-- 过期状态 -->
    <view v-if="expired" class="expired-container">
      <text class="expired-text">分享链接已过期</text>
    </view>
  </view>
</template>

<script>
import { shareApi } from '@/api/config';
import { getFullImageUrl } from '@/utils/image';
import templateService from '@/utils/template';
export default {
  data() {
    return {
      token: '',
      article: null,
      imageList: [],
      loading: true,
      error: false,
      errorMessage: '',
      expired: false,
      current: 0,
      detailTemplate: '',
      renderedTemplate: '',
      templateLoadStatus: {
        success: false,
        message: ''
      }
    };
  },
  onLoad(options) {
    this.token = options.token || '';
    if (!this.token) {
      this.error = true;
      this.errorMessage = '无效的分享链接';
      this.loading = false;
      return;
    }
    this.loadArticle();
  },
  onShareAppMessage() {
    return {
      title: this.article?.title || '文章分享',
      path: `/pages/shared/article?token=${this.token}`
    };
  },
  onShareTimeline() {
    return {
      title: this.article?.title || '文章分享',
      query: `token=${this.token}`,
      imageUrl: this.imageList[0] ? this.getImageUrl(this.imageList[0].url || this.imageList[0]) : ''
    };
  },
  methods: {
    async loadArticle() {
      this.loading = true;
      this.error = false;
      try {
        const res = await shareApi.view(this.token);
        if (res.code === 200 && res.data && res.data.content) {
          const content = res.data.content;
          // 处理图片列表
          let imageList = [];
          if (content.contentImg) {
            try {
              const imgs = JSON.parse(content.contentImg);
              if (Array.isArray(imgs)) {
                imageList = imgs;
              }
            } catch (e) {
              imageList = [];
            }
          }
          this.article = {
            title: content.contentTitle || '',
            author: content.contentAuthor || '',
            createTime: content.contentDatetime || '',
            views: content.contentHit || 0,
            content: content.contentDetails || '',
            description: content.contentDescription || ''
          };
          this.imageList = imageList;
          // 新增：加载分类信息和模板
          if (content.categoryId) {
            await this.loadCategoryAndTemplate(content.categoryId);
          } else {
            this.renderedTemplate = '';
          }
        } else if (res.code === 403) {
          this.expired = true;
        } else {
          this.error = true;
          this.errorMessage = res.msg || '加载失败，请重试';
        }
      } catch (error) {
        this.error = true;
        this.errorMessage = '网络错误，请重试';
      } finally {
        this.loading = false;
      }
    },
    async loadCategoryAndTemplate(categoryId) {
      try {
        // 查询分类信息
        const categoryRes = await shareApi.getCategoryById ? await shareApi.getCategoryById(categoryId) : null;
        let category = null;
        if (categoryRes && categoryRes.code === 200) {
          category = categoryRes.data;
        }
        // 查询模板
        let template = '';
        if (category) {
          template = await templateService.getCategoryDetailTemplate(category);
        }
        this.detailTemplate = template;
        // 渲染模板
        if (template) {
          // 扁平化数据结构，便于 mustache 渲染
          const templateData = {
            ...(this.article || {}),
            category: category
          };
          const rendered = templateService.parseTemplate(template, templateData);
          if (rendered) {
            this.renderedTemplate = rendered;
          } else {
            this.renderedTemplate = '';
          }
        } else {
          this.renderedTemplate = '';
        }
      } catch (e) {
        this.renderedTemplate = '';
      }
    },
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    getImageUrl(url) {
      return getFullImageUrl(url);
    },
    previewImage(images, currentIndex) {
      const urls = images.map(img => this.getImageUrl(img.url || img));
      uni.previewImage({
        urls: urls,
        current: urls[currentIndex],
        loop: true,
        indicator: 'number'
      });
    },
    onSwiperChange(e) {
      this.current = e.detail.current;
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 15px;
  background-color: #f5f5f5;
  min-height: 100vh;
}
.top-swiper-wrap {
  position: relative;
  margin-bottom: 16px;
}
.top-swiper {
  width: 100%;
  height: 400rpx;
}
.swiper-image {
  width: 100%;
  height: 400rpx;
  border-radius: 12rpx;
}
.img-count {
  position: absolute;
  right: 24rpx;
  bottom: 16rpx;
  color: #fff;
  background: rgba(0,0,0,0.4);
  border-radius: 20rpx;
  padding: 4rpx 12rpx;
  font-size: 24rpx;
}
.article-header {
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 10px;
}
.article-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  line-height: 1.4;
  margin-bottom: 10px;
}
.article-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.meta-item {
  font-size: 12px;
  color: #999;
}
.article-desc {
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 10px;
}
.desc-text {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}
.image-list {
  margin-top: 20rpx;
}
.list-image {
  width: 100%;
  margin-bottom: 16rpx;
  border-radius: 12rpx;
}
.article-content {
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 10px;
}
.content-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}
.content-text {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}
.share-tip {
  margin-top: 40rpx;
  text-align: center;
  color: #999;
  font-size: 26rpx;
}
.loading, .empty-state {
  padding: 16px 0;
  text-align: center;
}
.loading-text, .empty-text {
  font-size: 14px;
  color: #999;
}
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  padding: 20px;
}
.error-text {
  font-size: 16px;
  color: #666;
  margin-bottom: 20px;
  text-align: center;
}
.retry-btn {
  padding: 12px 24px;
  background-color: #007aff;
  color: #fff;
  border-radius: 6px;
  font-size: 16px;
}
.expired-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 80vh;
}
.expired-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 30rpx;
}
</style> 
